import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, DatePicker, Row, Col, Statistic, message, Tag } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

// 获取积分变动记录列表
const fetchPointsLogs = async (params) => {
  return request('/api/v1/member/points/log', {
    method: 'GET',
    params,
  });
};

// 获取会员列表（用于下拉选择）
const fetchMembers = async () => {
  return request('/api/v1/member', {
    method: 'GET',
    params: {
      page: 1,
      page_size: 1000,
      status: 'active',
    },
  });
};

const MemberPoints = () => {
  const [pointsLogs, setPointsLogs] = useState([]);
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [statistics, setStatistics] = useState({
    totalPoints: 0,
    totalIncrease: 0,
    totalDecrease: 0,
  });

  // 获取积分变动记录列表
  const fetchPointsLogList = async () => {
    try {
      setLoading(true);
      const res = await fetchPointsLogs({
        page: pagination.current,
        page_size: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setPointsLogs(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
        // 设置统计数据
        if (res.data.statistics) {
          setStatistics(res.data.statistics);
        }
      } else {
        message.error(res.message || '获取积分变动记录列表失败');
      }
    } catch (error) {
      console.error('获取积分变动记录列表出错:', error);
      message.error('获取积分变动记录列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取会员列表
  const fetchMemberList = async () => {
    try {
      const res = await fetchMembers();
      if (res.success) {
        setMembers(res.data.list || []);
      } else {
        message.error(res.message || '获取会员列表失败');
      }
    } catch (error) {
      console.error('获取会员列表出错:', error);
      message.error('获取会员列表失败');
    }
  };

  useEffect(() => {
    fetchPointsLogList();
    fetchMemberList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination({
      ...pagination,
    });
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};

    if (values.member_id) {
      params.member_id = values.member_id;
    }

    if (values.type) {
      params.type = values.type;
    }

    if (values.order_no) {
      params.order_no = values.order_no;
    }

    if (values.dateRange && values.dateRange[0] && values.dateRange[1]) {
      params.start_time = moment(values.dateRange[0]).startOf('day').unix();
      params.end_time = moment(values.dateRange[1]).endOf('day').unix();
    }

    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 获取积分变动类型名称
  const getPointsTypeName = (type) => {
    switch (type) {
      case 1:
        return '消费获得';
      case 2:
        return '管理员调整';
      case 3:
        return '活动奖励';
      case 4:
        return '签到奖励';
      case 5:
        return '积分兑换';
      default:
        return '未知类型';
    }
  };

  // 获取积分变动类型颜色
  const getPointsTypeColor = (type) => {
    switch (type) {
      case 1:
        return 'blue';
      case 2:
        return 'purple';
      case 3:
        return 'green';
      case 4:
        return 'cyan';
      case 5:
        return 'orange';
      default:
        return 'default';
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '会员信息',
      dataIndex: 'member_id',
      key: 'member_id',
      render: (text) => {
        const member = members.find(m => m.id === text);
        return member ? `${member.name} (${member.phone})` : text;
      },
    },
    {
      title: '变动积分',
      dataIndex: 'points',
      key: 'points',
      render: (text) => {
        return (
          <span style={{ color: text > 0 ? '#52c41a' : '#f5222d' }}>
            {text > 0 ? `+${text}` : text}
          </span>
        );
      },
    },
    {
      title: '变动类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => (
        <Tag color={getPointsTypeColor(text)}>{getPointsTypeName(text)}</Tag>
      ),
    },
    {
      title: '变动前积分',
      dataIndex: 'before_points',
      key: 'before_points',
    },
    {
      title: '变动后积分',
      dataIndex: 'after_points',
      key: 'after_points',
    },
    {
      title: '关联订单',
      dataIndex: 'order_no',
      key: 'order_no',
      render: (text) => text || '-',
    },
    {
      title: '变动描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      render: (text) => text || '-',
    },
    {
      title: '变动时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => moment(text * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  return (
    <PageContainer title="会员积分记录">
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="总积分变动次数"
              value={pagination.total}
              suffix="次"
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="总增加积分"
              value={statistics.totalIncrease || 0}
              valueStyle={{ color: '#3f8600' }}
              prefix="+"
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="总减少积分"
              value={Math.abs(statistics.totalDecrease || 0)}
              valueStyle={{ color: '#cf1322' }}
              prefix="-"
            />
          </Col>
        </Row>
      </Card>

      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="member_id" label="会员">
            <Select
              placeholder="请选择会员"
              style={{ width: 200 }}
              allowClear
              showSearch
              optionFilterProp="children"
            >
              {members.map(member => (
                <Option key={member.id} value={member.id}>{member.name} ({member.phone})</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="type" label="变动类型">
            <Select placeholder="请选择变动类型" style={{ width: 150 }} allowClear>
              <Option value={1}>消费获得</Option>
              <Option value={2}>管理员调整</Option>
              <Option value={3}>活动奖励</Option>
              <Option value={4}>签到奖励</Option>
              <Option value={5}>积分兑换</Option>
            </Select>
          </Form.Item>
          <Form.Item name="order_no" label="订单号">
            <Input placeholder="请输入订单号" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="dateRange" label="变动时间">
            <RangePicker style={{ width: 250 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={pointsLogs}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>
    </PageContainer>
  );
};

export default MemberPoints;